package cn.com.project.config.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Aspect
@Component
public class ParamAspect {
    private static final Logger logger = LoggerFactory.getLogger(ParamAspect.class);

    @Pointcut("execution(public * cn.com.project.web..controller..*(..))")
    public void log() {

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String url = request.getRequestURL().toString();
            String method = request.getMethod();
            String remoteAddr = request.getRemoteAddr();
            String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
            StringBuffer sb = new StringBuffer();
            if (joinPoint.getArgs().length > 0) {
                for (Object o : joinPoint.getArgs()) {
                    if (o instanceof HttpServletRequest) {
                        Enumeration<String> parameterNames = ((HttpServletRequest) o).getParameterNames();
                        while (parameterNames.hasMoreElements()) {
                            String key = parameterNames.nextElement();
                            sb.append(key + "=" + ((HttpServletRequest) o).getParameter(key) + "&");
                        }
                    }
                }
                if (sb.lastIndexOf("&") != -1) sb.deleteCharAt(sb.lastIndexOf("&"));
            }
            logger.info("\nController:{} \nIP:{} \n" +
                            "{} {}\n {}",
                    classMethod, remoteAddr,
                    url, method, sb.toString());
        } catch (Exception e) {
            logger.error("Get param error", e);
        }
    }

}
